import { ipcMain, BrowserWindow } from 'electron';
import { browserManager } from '../core/browserManager';
import { generateUserAgent, getDefaultChromeUserDataDir } from '../utils/browser';

// 设置IPC处理器
export function setupIpcHandlers(mainWindow: BrowserWindow|null) {
  // 生成User Agent
  ipcMain.handle('generate-user-agent', () => {
    return generateUserAgent();
  });

  // 获取浏览器配置列表
  ipcMain.handle('get-browser-configs', async () => {
    try {
      return browserManager.getAllConfigs();
    } catch (error) {
      console.error('Failed to get browser configs:', error);
      return { success: false, error: error instanceof Error ? error.message : '获取浏览器配置失败' };
    }
  });

  // 获取默认用户数据目录
  ipcMain.handle('get-default-user-data-dir', async () => {
    try {
      const defaultUserDataDir = getDefaultChromeUserDataDir();
      return { success: true, path: defaultUserDataDir };
    } catch (error) {
      console.error('Failed to get default user data directory:', error);
      return { success: false, error: error instanceof Error ? error.message : '获取默认用户数据目录失败' };
    }
  });

  // 保存浏览器配置
  ipcMain.handle('save-browser-config', async (event, config) => {
    try {
      if (!config || typeof config !== 'object') {
        throw new Error('无效的配置数据');
      }
      browserManager.saveConfig(config);
      return { success: true };
    } catch (error) {
      console.error('Failed to save browser config:', error);
      return { success: false, error: error instanceof Error ? error.message : '保存浏览器配置失败' };
    }
  });

  // 删除浏览器配置
  ipcMain.handle('delete-browser-config', async (event, id) => {
    try {
      if (!id || typeof id !== 'string') {
        throw new Error('无效的配置ID');
      }
      browserManager.deleteConfig(id);
      return { success: true };
    } catch (error) {
      console.error('Failed to delete browser config:', error);
      return { success: false, error: error instanceof Error ? error.message : '删除浏览器配置失败' };
    }
  });

  // 启动浏览器实例
  ipcMain.handle('launch-browser', async (event, config) => {
    try {
      if (!config || typeof config !== 'object') {
        throw new Error('无效的配置数据');
      }
      await browserManager.launchBrowser(config);
      return { success: true, id: config.id };
    } catch (error) {
      console.error('Failed to launch browser:', error);
      return { 
        success: false, 
        error: error instanceof Error ? error.message : '启动浏览器失败'
      };
    }
  });

  // 停止浏览器实例
  ipcMain.handle('stop-browser', async (event, id) => {
    try {
      if (!id || typeof id !== 'string') {
        throw new Error('无效的实例ID');
      }
      await browserManager.stopBrowser(id);
      return { success: true };
    } catch (error) {
      console.error('Failed to stop browser:', error);
      return { 
        success: false, 
        error: error instanceof Error ? error.message : '停止浏览器失败'
      };
    }
  });

  // 获取浏览器状态
  ipcMain.handle('get-browser-status', (event, id) => {
    try {
      if (!id || typeof id !== 'string') {
        throw new Error('无效的实例ID');
      }
      const status = browserManager.getBrowserStatus(id);
      return status || { isRunning: false, lastChecked: Date.now(), inProgress: false };
    } catch (error) {
      console.error('Failed to get browser status:', error);
      return { isRunning: false, lastChecked: Date.now(), inProgress: false };
    }
  });

  // 获取所有浏览器状态
  ipcMain.handle('get-all-browser-statuses', () => {
    try {
      const statusMap = browserManager.getAllBrowserStatuses();
      // 将Map转换为普通对象以确保IPC传输正确
      const statusObj: { [key: string]: any } = {};
      statusMap.forEach((status, id) => {
        statusObj[id] = {
          isRunning: Boolean(status.isRunning),
          lastChecked: Number(status.lastChecked),
          inProgress: Boolean(status.inProgress),
          action: status.action
        };
      });
      return statusObj;
    } catch (error) {
      console.error('Failed to get all browser statuses:', error);
      return {};
    }
  });

  // 设置状态更新事件转发
  browserManager.on('statusUpdate', (id: string, status: any) => {
    if (mainWindow && !mainWindow.isDestroyed()) {
      mainWindow.webContents.send('browser-status-update', id, status);
    }
  });
}